{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests \n",
    "import time\n",
    "from bs4 import BeautifulSoup\n",
    "import lxml\n",
    "import json\n",
    "from Crypto.Cipher import AES\n",
    "import base64\n",
    "import os\n",
    "import binascii\n",
    "from builtins import pow\n",
    "from builtins import int\n",
    "from builtins import map\n",
    "from builtins import chr\n",
    "import sqlite3 as mysql"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "header = {'Host': 'music.163.com',\n",
    "          'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0',\n",
    "          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n",
    "          'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',\n",
    "          'Accept-Encoding': 'gzip, deflate',\n",
    "          'Connection': 'keep-alive',\n",
    "          'Upgrade-Insecure-Requests': '1',\n",
    "          'Cache-Control': 'max-age=0',\n",
    "          'cookie':'appver=1.5.2' \n",
    "         }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dic = {\"hlpretag\":\"<span class=\\'s-fc7\\'>\",\n",
    "       \"hlposttag\":\"</span>\",\n",
    "       \"limit\":\"30\",\n",
    "       \"offset\":\"2\",\n",
    "       \"s\":\"李志\",\n",
    "       \"total\":\"true\",\n",
    "       \"type\":\"1\",\n",
    "       \"csrf_token\":\"\"\n",
    "      }\n",
    "j8b_first_param = json.dumps(dic)\n",
    "j8b_second_param = \"010001\"\n",
    "j8b_third_param = (\"00e0b509f6259df8642dbc35662901477df22677e\"\n",
    "                   \"c152b5ff68ace615bb7b725152b3ab17a876aea8a\"\n",
    "                   \"5aa76d2e417629ec4ee341f56135fccf695280104\"\n",
    "                   \"e0312ecbda92557c93870114af6c9d05c4f7f0c36\"\n",
    "                   \"85b7a46bee255932575cce10b424d813cfe4875d3\"\n",
    "                   \"e82047b97ddef52741d546b8e289dc6935b3ece04\"\n",
    "                   \"62db0a22b8e7\")\n",
    "j8b_forth_param = \"0CoJUm6Qyw8W8jud\"\n",
    "iv = \"0102030405060708\"\n",
    "text = json.dumps(dic)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def AES_encrypt(text, secKey, iv='0102030405060708'):\n",
    "    pad = 16 - len(text) % 16\n",
    "    text = text + chr(pad) * pad\n",
    "    encryptor = AES.new(secKey, 2, '0102030405060708')\n",
    "    ciphertext = encryptor.encrypt(text)\n",
    "    encrypt_text_new = base64.b64encode(ciphertext).decode('utf-8')\n",
    "    return encrypt_text_new\n",
    "\n",
    "def createSecKey():\n",
    "    return binascii.hexlify(os.urandom(16))[:16]\n",
    "\n",
    "def get_params(text,secKey):\n",
    "    iv = \"0102030405060708\"\n",
    "    first_key = j8b_forth_param\n",
    "    h_encText_one = AES_encrypt(text, first_key)\n",
    "    h_encText_two = AES_encrypt(h_encText_one,secKey)\n",
    "    return h_encText_two\n",
    "\n",
    "def get_encSecKey(text, pubkey, moduls):\n",
    "    text = text[::-1]\n",
    "    rs = pow(int(binascii.hexlify(text), 16), int(pubkey, 16), int(moduls, 16))\n",
    "    return format(rs, 'x').zfill(256)\n",
    "\n",
    "secKey = createSecKey()\n",
    "encText = get_params(text, secKey)\n",
    "encSecKey = get_encSecKey(secKey, j8b_second_param, j8b_third_param)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'encSecKey': '3fc7010e8618b74b3f38794d9d942f003b332ab4490ae363eb991d5b889213c34abd60678ff270df2abf19342b9c409ee0bb04013cc2ae00d311d52f8a9ac40a19f797ef40ee361980a8bc3d040d9272dab475622cbace7b1a5e2815254f76aaf9428dba459a0a132295b8749ee2dd1aac44008b8de030c174b41f85633b7138',\n",
       " 'params': 'RhOFa/NZ/8r63jnXzCjR9HVDQH7z1h9QdUzg+gSI+kbg8f8zfQnfR136LVMdmuGSPgSdNzR5mlUDmr/NzcOqEFLa8wKlwZytIhtHMhVWzOKOu6wUb2E76u/52ZxLW/E0c3w6fRGA7y3w00lwTrM0PP4Vw+ZyGTBcmeSZFONeDxea3hf4ekRPEbCqzudFdhzYkK28egqzAViV4FOLbDTCP4wAmpCbQATypM17Xga/2eHJxKo4ct/Xlasr2M8h+dl2Y95RCu+5tRTbg8CZyHAVmCW8mw29fzxnPMr8Kh/ALxY='}"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "data = {\n",
    "     'params': encText,\n",
    "    'encSecKey': encSecKey\n",
    "    }\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='\n",
    "# response = requests.post(url, data=data, headers=header)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('你离开了南京，从此没有人和我说话', 26508242, 96000)"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def get_name_id(count):\n",
    "    url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='\n",
    "    response = requests.post(url, data=data, headers=header)\n",
    "    name = response.json()['result']['songs'][count]['name']\n",
    "    name_id = response.json()['result']['songs'][count]['id']\n",
    "    name_br = response.json()['result']['songs'][count]['l']['br']\n",
    "    return name, name_id, name_br\n",
    "name, name_id, name_br = get_name_id(3)\n",
    "name, name_id, name_br"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'http://m10.music.126.net/20170626001313/13f5d920d4919c97e30e3d92719d7f8c/ymusic/534d/12e3/11d8/eb843de06316340562b81988e66f7fb8.mp3'"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def getlink(name_id, name_br):\n",
    "    url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='\n",
    "    ids = \"[\" + str(name_id) + \"]\"\n",
    "    secKey = createSecKey()\n",
    "    param = {\"ids\":ids,\n",
    "            \"br\":name_br,\n",
    "            \"csrf_token\":\"\"}\n",
    "    text = json.dumps(param)\n",
    "    data = {'params': get_params(text, secKey),\n",
    "            'encSecKey': get_encSecKey(secKey, j8b_second_param, j8b_third_param)\n",
    "           }\n",
    "    response = requests.post(url, headers=header, data=data)\n",
    "    return response.json()\n",
    "mp3_url = getlink(name_id, name_br)['data'][0]['url']\n",
    "mp3_url"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# import webbrowser as browser\n",
    "# browser.open(mp3.url)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ok\n"
     ]
    }
   ],
   "source": [
    "from urllib import request\n",
    "result = request.urlopen(mp3_url)\n",
    "path = 'H:\\\\Netease\\\\'+ name+'.mp3'\n",
    "with open(path, 'wb') as f:\n",
    "    f.writelines(result.readlines())\n",
    "print('ok')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "insert into music (name, name_id, name_br) values ('天空之城',26508186,96000)\n",
      "insert into music (name, name_id, name_br) values ('关于郑州的记忆',25867002,96000)\n",
      "insert into music (name, name_id, name_br) values ('梵高先生',26508240,96000)\n",
      "insert into music (name, name_id, name_br) values ('下雨',26508231,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起',26523120,96000)\n",
      "insert into music (name, name_id, name_br) values ('你离开了南京，从此没有人和我说话',26508242,96000)\n",
      "insert into music (name, name_id, name_br) values ('山阴路的夏天',26508232,96000)\n",
      "insert into music (name, name_id, name_br) values ('热河',29724295,96000)\n",
      "insert into music (name, name_id, name_br) values ('定西',29724292,96000)\n",
      "insert into music (name, name_id, name_br) values ('黑色信封',478491642,96000)\n",
      "insert into music (name, name_id, name_br) values ('米店',26522011,96000)\n",
      "insert into music (name, name_id, name_br) values ('这个世界会好吗2015',31381877,96000)\n",
      "insert into music (name, name_id, name_br) values ('墙上的向日葵(2014i/O版)',30212877,96000)\n",
      "insert into music (name, name_id, name_br) values ('忽然',26353044,96000)\n",
      "insert into music (name, name_id, name_br) values ('鸵鸟&天空之城&我们不能失去信仰(2014i/O版)',30967318,96000)\n",
      "insert into music (name, name_id, name_br) values ('谁他妈没织过毛衣',28590174,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起',478491643,96000)\n",
      "insert into music (name, name_id, name_br) values ('墙上的向日葵',478490650,96000)\n",
      "insert into music (name, name_id, name_br) values ('杭州',26508235,96000)\n",
      "insert into music (name, name_id, name_br) values ('苍井空',26508183,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起2013版[Live]',28406900,96000)\n",
      "insert into music (name, name_id, name_br) values ('结婚',26508184,96000)\n",
      "insert into music (name, name_id, name_br) values ('春末的南方城市',26508238,96000)\n",
      "insert into music (name, name_id, name_br) values ('再见',26522014,96000)\n",
      "insert into music (name, name_id, name_br) values ('想起了她',26508244,96000)\n",
      "insert into music (name, name_id, name_br) values ('回答',478490652,96000)\n",
      "insert into music (name, name_id, name_br) values ('下雨&董卓瑶&忽然(2014i/O版)',30967312,96000)\n",
      "insert into music (name, name_id, name_br) values ('被禁忌的游戏',26508205,96000)\n",
      "insert into music (name, name_id, name_br) values ('杭州',478491640,96000)\n"
     ]
    }
   ],
   "source": [
    "# with open('H:\\\\Netease\\\\关于郑州的记忆.mp3', 'wb') as f:\n",
    "#     f.writelines(result.readlines())\n",
    "# print('ok')\n",
    "for i in range(29):\n",
    "    name, name_id, name_br = get_name_id(i)\n",
    "# #     time.sleep(0.001)\n",
    "# #     mp3_url = getlink(name_id, name_br)['data'][0]['url']\n",
    "# #     result = request.urlopen(mp3_url)\n",
    "# #     path = 'H:\\\\Netease\\\\'+ name+'.mp3'\n",
    "# #     with open(path, 'wb') as f:\n",
    "# #         f.writelines(result.readlines())\n",
    "# #     print(name, 'is ok')\n",
    "    insert = \"insert into music (name, name_id, name_br) values \"+ \"('{0}',{1},{2})\".format(name, name_id, name_br)\n",
    "    print(insert)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<sqlite3.Cursor at 0xc3528a6420>"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "conn = mysql.connect('H:\\\\Net3.db')\n",
    "cursor = conn.cursor()\n",
    "# try:\n",
    "create_table = \"CREATE TABLE IF NOT EXISTS MUSIC (name VARCHAR(256), name_id INT PRIMERY KEY , name_br INT )\"\n",
    "cursor.execute(create_table)\n",
    "# except:\n",
    "#     print('table music already exists')\n",
    "# print('ok')\n",
    "# for i in range(29):\n",
    "#     name, name_id, name_br = get_name_id(i)\n",
    "#     time.sleep(0.001)\n",
    "#     mp3_url = getlink(name_id, name_br)['data'][0]['url']\n",
    "#     result = request.urlopen(mp3_url)\n",
    "#     path = 'H:\\\\Netease\\\\'+ name+'.mp3'\n",
    "#     with open(path, 'wb') as f:\n",
    "#         f.writelines(result.readlines())\n",
    "#     print(name, 'is ok')\n",
    "#     insert = \"insert into music (name, name_id, name_br) values \"+ \"('{0}',{1},{2})\".format(name, name_id, name_br)\n",
    "#     print(insert)\n",
    "#     print(insert)\n",
    "# #     try:\n",
    "# #         cursor.execute(insert)\n",
    "#     except:\n",
    "#         print('wrong')\n",
    "# conn.commit()\n",
    "# conn.close()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# conn = mysql.connect('H:\\\\Net3.db')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<sqlite3.Cursor at 0xc35271d420>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "curcor = conn.cursor()\n",
    "cursor.execute(\"INSERT INTO MUSIC (name, name_id, name_br) VALUES ('天空之城',26508186,320000)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "ProgrammingError",
     "evalue": "Cannot operate on a closed cursor.",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mProgrammingError\u001b[0m                          Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-119-baf82ce3a73d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcursor\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mexecute\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"INSERT INTO net (name, name_id, name_br) VALUES ('和你在一起',26523120,320000)\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      2\u001b[0m \u001b[0mcursor\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mconn\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcommit\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0mconn\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mclose\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mProgrammingError\u001b[0m: Cannot operate on a closed cursor."
     ]
    }
   ],
   "source": [
    "cursor.execute(\"INSERT INTO MUSIC (name, name_id, name_br) VALUES ('和你在一起',26523120,320000)\")\n",
    "cursor.close()\n",
    "conn.commit()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "insert into music (name, name_id, name_br) values ('梵高先生',26508240,96000)\n",
      "insert into music (name, name_id, name_br) values ('下雨',26508231,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起',26523120,96000)\n",
      "insert into music (name, name_id, name_br) values ('你离开了南京，从此没有人和我说话',26508242,96000)\n",
      "insert into music (name, name_id, name_br) values ('山阴路的夏天',26508232,96000)\n",
      "insert into music (name, name_id, name_br) values ('热河',29724295,96000)\n",
      "insert into music (name, name_id, name_br) values ('定西',29724292,96000)\n",
      "insert into music (name, name_id, name_br) values ('黑色信封',478491642,96000)\n",
      "insert into music (name, name_id, name_br) values ('米店',26522011,96000)\n",
      "insert into music (name, name_id, name_br) values ('这个世界会好吗2015',31381877,96000)\n",
      "insert into music (name, name_id, name_br) values ('墙上的向日葵(2014i/O版)',30212877,96000)\n",
      "insert into music (name, name_id, name_br) values ('忽然',26353044,96000)\n",
      "insert into music (name, name_id, name_br) values ('鸵鸟&天空之城&我们不能失去信仰(2014i/O版)',30967318,96000)\n",
      "insert into music (name, name_id, name_br) values ('谁他妈没织过毛衣',28590174,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起',478491643,96000)\n",
      "insert into music (name, name_id, name_br) values ('墙上的向日葵',478490650,96000)\n",
      "insert into music (name, name_id, name_br) values ('杭州',26508235,96000)\n",
      "insert into music (name, name_id, name_br) values ('苍井空',26508183,96000)\n",
      "insert into music (name, name_id, name_br) values ('和你在一起2013版[Live]',28406900,96000)\n",
      "insert into music (name, name_id, name_br) values ('结婚',26508184,96000)\n",
      "insert into music (name, name_id, name_br) values ('春末的南方城市',26508238,96000)\n",
      "insert into music (name, name_id, name_br) values ('再见',26522014,96000)\n",
      "insert into music (name, name_id, name_br) values ('想起了她',26508244,96000)\n",
      "insert into music (name, name_id, name_br) values ('回答',478490652,96000)\n",
      "insert into music (name, name_id, name_br) values ('下雨&董卓瑶&忽然(2014i/O版)',30967312,96000)\n",
      "insert into music (name, name_id, name_br) values ('被禁忌的游戏',26508205,96000)\n",
      "insert into music (name, name_id, name_br) values ('杭州',478491640,96000)\n",
      "insert into music (name, name_id, name_br) values ('结婚 (2016 unplugged)',424477863,96000)\n",
      "insert into music (name, name_id, name_br) values ('采蘑菇的小姑娘',435948316,96000)\n"
     ]
    }
   ],
   "source": [
    "for i in range(29):\n",
    "    name, name_id, name_br = get_name_id(i)\n",
    "    insert = \"insert into music (name, name_id, name_br) values \"+ \"('{0}',{1},{2})\".format(name, name_id, name_br)\n",
    "    print(insert)\n",
    "    cursor.execute(insert)\n",
    "conn.commit()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cursor.close()\n",
    "conn.commit()\n",
    "conn.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
